package com.gjy.batch.config;

import com.gjy.batch.module.StudentInfo;
import com.gjy.batch.module.file.StudentFile;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-07-03 08:41:20
 */
@Configuration
@EnableBatchProcessing(modular = true)
public class SpringBatchConfiguration {

    @Resource
    private JobBuilderFactory jobBuilderFactory;
    @Resource
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public Step csvToDbStep(ItemReader<StudentFile> studentInfoReader,
                            ItemProcessor<StudentFile, StudentInfo> studentInfoProfessor,
                            ItemWriter<StudentInfo> studentInfoWriter) {

        return stepBuilderFactory.get("csvToDbStep")
                .<StudentFile, StudentInfo>chunk(100) // 每100条数据提交一次
                .reader(studentInfoReader)
                .processor(studentInfoProfessor)
                .writer(studentInfoWriter)
                .build();
    }

    @Bean
    public Job importStudentJob(Step csvToDbStep) {
        return jobBuilderFactory.get("importStudentJob")
                .incrementer(new RunIdIncrementer()) // 允许重复运行
                .start(csvToDbStep)
                .build();
    }

}
